var express = require('express');
const {
  getAllCates,
  addCate,
  getCount,
  _getAllCates,
  getCateById,
  updateCate,
  delCate
} = require("../models/cateModel")
var router = express.Router();


/* GET home page. */
router.get('/cateList', async function (req, res) {
  // 发送两个数据 当前页 一页多少条
  const {
    curr = 1, pageSize = 2
  } = req.query;
  console.log(curr, pageSize);
  /* curr = curr?curr:1;
  pageSize = pageSize?pageSize:2; */
  let cates = await getAllCates({
    pageSize,
    curr
  });
  // 数据总条数
  let count = await getCount();

  res.render('cateList', {
    cates,
    count,
    curr
  });
});
// 增加分类
router.get("/cateAdd", async (req, res) => {
  // 获取所有的分类数据 在页面上渲染
  let cates = await _getAllCates();
  res.render("cateAdd", {
    cates
  })
})
// 增加分类 提交
router.post("/cateAdd", (req, res) => {
  console.log(req.body)
  // 增加分类
  addCate(req.body).then(re => {
    res.send({
      code: 0,
      msg: "增加成功"
    })
  }).catch(err => {
    res.send({
      code: -1,
      msg: "增加失败"
    })
  })

})

// 编辑分类
router.get("/cateEdit", async (req, res) => {
  // 获取所有的分类数据 在页面上渲染

  let {
    cateId
  } = req.query;
  // 获取对应这条分类的数据、
  let cate = await getCateById(cateId);
  console.log(cate);
  let cates = await _getAllCates();
  res.render("cateEdit", {
    cates,
    cate
  })
})
// 增加分类 提交
router.post("/cateEdit", (req, res) => {
  console.log(req.body)
  const params = req.body;
  // 增加分类
  updateCate({
    query: {
      _id: params._id
    },
    content: params
  }).then(re => {
    res.send({
      code: 0,
      msg: '更新成功'
    })
  }).catch(err => {
    res.send({
      code: -1,
      msg: '更新失败'
    })
  });

})

// 删除文章

router.post("/editDel", (req, res) => {
  console.log(req.body)
  delCate(req.body).then(re=>{
    res.send({
      code: 0,
      msg: "删除成功"
    })
  }).catch(err=>{
    res.send({
      code: -1,
      msg: "删除失败"
    })
  })
  
})



module.exports = router;